/******************************************************************************
 * @File name   :      MaintainDealerServiceimpl.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 15, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 15, 2015 7:06:11 PM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.masterdata.service.impl;

import java.io.File;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cap.bts.commonfunc.common.constant.SmSendStatus;
import com.cap.bts.commonfunc.sms.domain.SmContent;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.card.service.ICardExportService;
import com.cap.bts.crmdp.dealer.card.util.CSVUtils;
import com.cap.bts.crmdp.dealer.masterdata.constants.MaintainMasterDataConstants;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMaintainDealerDao;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMarsDataConversionMemberDao;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMarsDataConversionPortfolioDao;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.dto.DataConvertStoredProcedure;
import com.cap.bts.crmdp.dealer.masterdata.dto.DataFixPrcResultDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerChangeDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerQueryDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerResultsDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DmsDataFixResultDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.MaintainMasterDataSubmitDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.MarsDataConversionMemberDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.MarsDataConversionPortfolioDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.SmsSendDto;
import com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.webservice.dc.DataConversionQueue;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.FileImportUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.dto.SMSTextMessage;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.sms.util.HttpSMSProcessUtil;
import com.jcraft.jsch.ChannelSftp;

/**
 * 
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MaintainDealerServiceimpl extends BaseServiceImpl implements IMaintainDealerService {

	private static final Logger LOGGER = Logger.getLogger(MaintainDealerServiceimpl.class);
	
	@Resource(name = "maintainDealerDao")
	private IMaintainDealerDao maintainDealerDao;
	@Autowired
    ICardExportService cardExportService;
	@Autowired
    private ICodeMapping codeMappingService;
	@Autowired
	private IMarsDataConversionMemberDao marsDataConversionMemberDao;
	@Autowired
	private IMarsDataConversionPortfolioDao marsDataConversionPortfolioDao;
	@Autowired
	private ISmContentService smContentService;
	/* (non-Javadoc)
	 * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#getMaintainDealerEmployeeByDto(com.cap.bts.crmdp.dealer.masterdata.dto.DealerQueryDto)
	 */
	@Override
	public List<DealerResultsDto> getMaintainDealerByDto(DealerQueryDto dto) throws AppException {

		List<MasterDataDealerInfo> masterDataDealerInfo =  maintainDealerDao.getMaintainDealerInfoByDto(dto);
		List<DealerResultsDto> dealerResultsDtoList = new ArrayList<DealerResultsDto>();
		
		for (int i = 0; i < masterDataDealerInfo.size(); i++) {
			DealerResultsDto dealerResultsDto = new DealerResultsDto();
			MasterDataDealerInfo info = masterDataDealerInfo.get(i);
			
			dealerResultsDto.setId(info.getId());
			dealerResultsDto.setDealerNum(info.getDealerNum());
			dealerResultsDto.setDealerName(info.getDealerName());
			dealerResultsDto.setDealerProgram(info.getDealerProgram());
			dealerResultsDto.setRegion(info.getRegion());

		
			dealerResultsDto.setAddress(info.getAddress());
			dealerResultsDto.setContactName(info.getContactName());
			dealerResultsDto.setContactPhone(info.getContactPhone());
			dealerResultsDto.setProvince(info.getProvinceName());
			dealerResultsDto.setCity(info.getCityName());
			
			dealerResultsDto.setDealerStatus(info.getDealerStatus());

			dealerResultsDtoList.add(dealerResultsDto);
		}
		return dealerResultsDtoList;
	}

	/*
	 * (non-Javadoc)
	 * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#saveDealer(com.cap.bts.crmdp.dealer.masterdata.dto.MaintainMasterDataSubmitDto)
	 */
	@Override
	public boolean saveDealer(MaintainMasterDataSubmitDto submitDto) throws AppException {

		boolean results = true;
		MasterDataDealerInfo dealerInfo = new MasterDataDealerInfo();
		
		try {
			dealerInfo.setDealerNum(submitDto.getDealerNum());
			dealerInfo.setDealerName(submitDto.getDealerName());
			dealerInfo.setDealerProgram(submitDto.getDealerProgram());
			dealerInfo.setRegion(submitDto.getRegion());
//			dealerInfo.setProvince(submitDto.getProvince())
//			dealerInfo.setCity(submitDto.getCity())
			dealerInfo.setAddress(submitDto.getAddress());
			dealerInfo.setContactName(submitDto.getContactName());
			dealerInfo.setContactPhone(submitDto.getContactPhone());
			dealerInfo.setDealerStatus(submitDto.getDealerStatus());
			
			CodeInfo ci = new CodeInfo();
			ci.setid(0L);
			
			dealerInfo.setProvince(ci);// test
			dealerInfo.setCity(ci);// test
			
			
			dealerInfo.setCreateBy(0L);
			dealerInfo.setCreateDate(new Date());
			
			dealerInfo.setLastUpdateBy(0L);
			dealerInfo.setLastUpdateDate(new Date());

			if(Utils.notNullAndNegative(submitDto.getId())){
				dealerInfo.setId(submitDto.getId());
				maintainDealerDao.update(dealerInfo);
				results = true;
			}else{
				maintainDealerDao.save(dealerInfo);
			}
		} catch (Exception e) {
			LOGGER.debug(e);
			return false;
		}

		return results;
	}

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月22日
     * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#getDealerByDealerNum(java.lang.String)
    **/
    @Override
    public MasterDataDealerInfo getDealerByDealerNum(String dealerNum) throws AppException {
        try {
            return maintainDealerDao.getDealerByDealerNum(dealerNum);
        } catch (Exception e) {
            LOGGER.info("getDealerByDealerNum", e);
            throw new AppException(CommonErrorConstants.SYSTEM_ERROR, e.getLocalizedMessage());
        }
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月22日
     * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#updateDealer(com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo)
    **/
    @Override
    public boolean updateDealer(MasterDataDealerInfo dealerInfo) throws AppException {
        try {
            maintainDealerDao.update(dealerInfo);
            return true;
        } catch (Exception e) {
            LOGGER.info("updateDealer", e);
            throw new AppException(CommonErrorConstants.SYSTEM_ERROR, e.getLocalizedMessage());
        }
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月24日
     * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#getDealerByOperationPwd(java.lang.String)
    **/
    @Override
    public boolean getDealerByOperationPwdAndDealerNum(String operationPwd,String dealerNum) throws AppException {
        return maintainDealerDao.getDealerByOperationPwdAndDealerNum(operationPwd,dealerNum)==null?false:true;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 20, 2015
     * @see com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService#getDearlerIntoByDealerId(java.lang.Long)
    **/
    @Override
    public List<MasterDataDealerInfo> getDearlerIntoByDealerIds(List<String> dearlerIds) throws AppException {
        StringBuilder sb=new StringBuilder();
        for(String dearId:dearlerIds){
            sb.append("'"+dearId+"',");
        }
        sb.deleteCharAt(sb.length()-1);
        return maintainDealerDao.getListByQuery("from MasterDataDealerInfo a where a.id in ("+sb.toString()+")");
    }

	@Override
	public File exportMemberFromDealer(String storeCode) throws AppException {
		List<Object[]> list = maintainDealerDao.exportMemberAndPackageFromDealer(storeCode);
		if(list != null && !list.isEmpty()){
			StringBuilder fileName = new StringBuilder();
			fileName.append(MaintainMasterDataConstants.MEMBER).append("_").append(storeCode);
			List exportData = new ArrayList<Map>();
			Map map = new LinkedHashMap();
            map.put("1", "pcode");
            map.put("2", "member_code");
            map.put("3", "member_name");
            map.put("4", "mobile");
            map.put("5", "car_plate");
            map.put("6", "store_code");
            Integer temp=0;
            for (Object[] obj : list) {
            	Map row= new LinkedHashMap<String, String>();
                temp++;
                row.put("1", obj[0]);
                row.put("2", obj[1]);
                row.put("3", obj[2]);
                row.put("4", obj[3]);
                row.put("5", obj[4]);
                row.put("6", obj[5]);
                exportData.add(row);
			}
            File file = CSVUtils.createCSVFile(exportData, map, "./", fileName.toString(),"GBK");
            return file;
		}
		return null;
	}

	@Override
	public File exportPortfolioFromDealer(String storeCode) throws AppException {
		List<Object[]> list = maintainDealerDao.exportPortfolioFromDealer(storeCode);
		if(list != null && !list.isEmpty()){
			StringBuilder fileName = new StringBuilder();
			fileName.append(MaintainMasterDataConstants.PORTFOLIO).append("_").append(storeCode);
			List exportData = new ArrayList<Map>();
			Map map = new LinkedHashMap();
            map.put("1", "pcode");
            map.put("2", "member_code");
            map.put("3", "member_name");
            map.put("4", "mobile");
            map.put("5", "car_plate");
            map.put("6", "card_no");
            map.put("7", "card_type");
            map.put("8", "store_code");
            map.put("9", "title");
            map.put("10", "STATUS");
            Integer temp=0;
            for (Object[] obj : list) {
            	Map row= new LinkedHashMap<String, String>();
                temp++;
                row.put("1", obj[0]);
                row.put("2", obj[1]);
                row.put("3", obj[2]);
                row.put("4", obj[3]);
                row.put("5", obj[4]);
                row.put("6", obj[5]);
                row.put("7", obj[6]);
                row.put("8", obj[7]);
                row.put("9", obj[8]);
                row.put("10", obj[9]);
                exportData.add(row);
			}
            File file = CSVUtils.createCSVFile(exportData, map, "./", fileName.toString(),"GBK");
            return file;
		}
		return null;
	}

	@Override
	public boolean downLodeMemberFile(String remoteFile, String remotePath, String localFile) throws AppException {
		//从SFTP上下载文件
		String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.DATACONVERT);
		try {
			if(sftpInfo != null){
				SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
				
				SFTPProcessor ftpUtil = new SFTPProcessor();
				ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
				
				if(channelSftp.isConnected()){
					ftpUtil.downloadFile(remoteFile, remotePath, localFile);
					ftpUtil.closeChannel();
					return true;
				}
				ftpUtil.closeChannel();
			}
		} catch (RuntimeException e) {
			LOGGER.info("downLodeMemberFile", e);
		} catch (Exception e) {
			LOGGER.info("downLodeMemberFile", e);
		}
		return false;
	}

	@Override
	public boolean downLodeProtfolioFile(String remoteFile, String remotePath, String localFile) throws AppException {
		String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.DATACONVERT);
		try {
			if(sftpInfo != null){
				SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
				
				SFTPProcessor ftpUtil = new SFTPProcessor();
				ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
				
				if(channelSftp.isConnected()){
					ftpUtil.downloadFile(remoteFile, remotePath, localFile);
					ftpUtil.closeChannel();
					return true;
				}
				ftpUtil.closeChannel();
			}
		} catch (RuntimeException e) {
			LOGGER.info("downLodeProtfolioFile", e);
		} catch (Exception e) {
			LOGGER.info("downLodeProtfolioFile", e);
		}
		return false;
	}
	
	/**
	 * 检查门店是否存在历史数据
	 * 
	 * @param dearNumber
	 * @return
	 */
	public boolean checkExistHistoryData(String dearNumber, boolean memberFlag, boolean portfolioFlag){
		List<String> list = marsDataConversionMemberDao.checkStoreCodeByStoreCode(dearNumber, memberFlag, portfolioFlag);
		if(list != null && !list.isEmpty()){
			return true;
		}
		return false;
	}
	
	
	/**
	 * 将数据写入表中
	 * 
	 * @param memberDtoList
	 * @param portfolioDtoList
	 * @return
	 */
	public boolean insertDTData(String batchId, List<MarsDataConversionMemberDto> memberDtoList, List<MarsDataConversionPortfolioDto> portfolioDtoList){
		if(memberDtoList != null && !memberDtoList.isEmpty()){
			try {
				marsDataConversionMemberDao.batchInsertMember(batchId, memberDtoList);
			} catch (Exception e) {
				LOGGER.error(e);
				return false;
			} 
		}
		
		if(portfolioDtoList != null && !portfolioDtoList.isEmpty()){
				try {
					marsDataConversionMemberDao.batchInsertPortfolio(batchId, portfolioDtoList);
				} catch (Exception e) {
					LOGGER.error(e);
					return false;
				}
		}
		return true;
	}

	@Override
	public String upLodeMemberFile(String storeCode) throws AppException {
		List<Object[]> list = maintainDealerDao.exportMemberResultFromDealer(storeCode);
		if(list != null && !list.isEmpty()){
			StringBuilder fileName = new StringBuilder();
			fileName.append(MaintainMasterDataConstants.MEMBER).append("_").append(storeCode);
			List exportData = new ArrayList();
			Map map = new LinkedHashMap();
			map.put("1", "line_num");
            map.put("2", "pcode");
            map.put("3", "member_code");
            map.put("4", "member_name");
            map.put("5", "mobile");
            map.put("6", "car_plate");
            map.put("7", "store_code");
            map.put("8", "mars_customer_code");
            map.put("9", "mars_vehicle_code");
            map.put("10", "mars_customer_name");
            map.put("11", "mars_phone_number");
            map.put("12", "status");
            map.put("13", "error_message");
            Integer temp=0;
            for (Object[] obj : list) {
            	Map row= new LinkedHashMap<String, String>();
                temp++;
                row.put("1", obj[2]);
                row.put("2", obj[3]);
                row.put("3", obj[4]);
                row.put("4", obj[5]);
                row.put("5", obj[6]);
                row.put("6", obj[7]);
                row.put("7", obj[8]);
                row.put("8", obj[9]);
                row.put("9", obj[10]);
                row.put("10", obj[11]);
                row.put("11", obj[12]);
                row.put("12", obj[13]);
                row.put("13", obj[14]);
                exportData.add(row);
			}
            try {
				File file = CSVUtils.createCSVFile(exportData, map, "./", fileName.toString(),"GBK");
				String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.DATACONVERT);
				if(sftpInfo != null && ! "".equals(sftpInfo)){
					SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
					SFTPProcessor ftpUtil = new SFTPProcessor();
					ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
					if(channelSftp.isConnected()){
						ftpUtil.uploadFile(file.getAbsolutePath(), fileName.toString() + ".csv", sftpProperties.getPath());
						ftpUtil.closeChannel();
						file.delete();
						return fileName.toString() + ".csv";
					}
					ftpUtil.closeChannel();
				}
			} catch (RuntimeException e) {
				throw new AppException("upLodeMemberFileError", e);
			} catch (Exception e) {
				throw new AppException("upLodeMemberFileError", e);
			}
		}
		return null;
	}

	@Override
	public String upLodePortfolioFile(String storeCode) throws AppException {
		List<Object[]> list = maintainDealerDao.exportPortfolioResultFromDealer(storeCode);
		if(list != null && !list.isEmpty()){
			StringBuilder fileName = new StringBuilder();
			fileName.append(MaintainMasterDataConstants.PORTFOLIO).append("_").append(storeCode);
			List exportData = new ArrayList();
			Map map = new LinkedHashMap();
			map.put("1", "Id");
            map.put("2", "pcode");
            map.put("3", "member_code");
            map.put("4", "member_name");
            map.put("5", "mobile");
            map.put("6", "mars_customer_code");
            map.put("7", "car_plate");
            map.put("8", "mars_car_no");
            map.put("9", "card_no");
            map.put("10", "dms_card_no");
            map.put("11", "card_type");
            map.put("12", "dms_card_type");
            map.put("13", "store_code");
            map.put("14", "title");
            map.put("15", "dms_title");
            map.put("16", "creation_date");
            map.put("17", "validate_date");
            map.put("18", "due_date");
            map.put("19", "dp_status");
            map.put("20", "dms_status");
            map.put("21", "coupon_type");
            map.put("22", "free_service_times");
            map.put("23", "times_of_use");
            map.put("24", "times_left");
            map.put("25", "status");
            map.put("26", "error_message");
            Integer temp=0;
            for (Object[] obj : list) {
            	Map row= new LinkedHashMap<String, String>();
                temp++;
                row.put("1", obj[2]);
                row.put("2", obj[3]);
                row.put("3", obj[4]);
                row.put("4", obj[5]);
                row.put("5", obj[6]);
                row.put("6", obj[7]);
                row.put("7", obj[8]);
                row.put("8", obj[9]);
                row.put("9", obj[10]);
                row.put("10", obj[11]);
                row.put("11", obj[12]);
                row.put("12", obj[13]);
                row.put("13", obj[14]);
                row.put("14", obj[15]);
                row.put("15", obj[16]);
                row.put("16", obj[17]);
                row.put("17", obj[18]);
                row.put("18", obj[19]);
                row.put("19", obj[20]);
                row.put("20", obj[21]);
                row.put("21", obj[22]);
                row.put("22", obj[23]);
                row.put("23", obj[24]);
                row.put("24", obj[25]);
                row.put("25", obj[26]);
                row.put("26", obj[27]);
                exportData.add(row);
			}
            try {
				File file = CSVUtils.createCSVFile(exportData, map, "./", fileName.toString(),"GBK");
				String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.DATACONVERT);
				if(sftpInfo != null && ! "".equals(sftpInfo)){
					SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
					SFTPProcessor ftpUtil = new SFTPProcessor();
					ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
					if(channelSftp.isConnected()){
						ftpUtil.uploadFile(file.getAbsolutePath(), fileName.toString() + ".csv", sftpProperties.getPath());
						ftpUtil.closeChannel();
						file.delete();
						return fileName.toString() + ".csv";
					}
					ftpUtil.closeChannel();
				}
			} catch (RuntimeException e) {
				throw new AppException("upLodePortfolioFileError", e);
			} catch (Exception e) {
				throw new AppException("upLodePortfolioFileError", e);
			}
		}
		return null;
	}
	
	
	/**
	 * 调用存储过程处理数据
	 * 
	 * @param dealerNum
	 * @param dataType PORTFOLIO or MEMBER
	 */
	public DataConvertStoredProcedure callPrcDataConversion(String dealerNum, boolean memberFlag, boolean portfolioFlag){
		Integer dealerId = Integer.parseInt(dealerNum);
		
		DataConvertStoredProcedure convertStoredProcedure = new DataConvertStoredProcedure();
		
		try {
			if(memberFlag){
				convertStoredProcedure = marsDataConversionMemberDao.callPrcDataConversion(dealerId, "MEMBER");
				
				if(StringUtils.startsWith(convertStoredProcedure.getReturnCode(), "E") && portfolioFlag){
					marsDataConversionMemberDao.callPrcDataConversion(dealerId, "PORTFOLIO");
					return convertStoredProcedure;
				}
			}
			
			if(portfolioFlag){
				convertStoredProcedure = marsDataConversionMemberDao.callPrcDataConversion(dealerId, "PORTFOLIO");
			}
			
		} catch (SQLException e) {
			LOGGER.error("", e);
			convertStoredProcedure.setReturnCode("EEE");
			convertStoredProcedure.setErrorMessage(e.getMessage());
		}
		
		
		return convertStoredProcedure;
	}

	@Override
	public List<DealerChangeDto> getAllDealerChange(DealerChangeDto dto) {
		List<Object[]> list = maintainDealerDao.getAllDealerChange(dto);
		if(list != null && !list.isEmpty()){
			List<DealerChangeDto> dealerChangeDtoList = new ArrayList<DealerChangeDto>();
			for (int i = 0; i < list.size(); i++) {
				DealerChangeDto dealerChangeDto = new DealerChangeDto();
				dealerChangeDto.setDealerNum(Utils.getString(list.get(i)[0]));
				dealerChangeDto.setDealerName(Utils.getString(list.get(i)[1]));
				
				Date date = Utils.getDate(list.get(i)[2]);
				
				dealerChangeDto.setChangeDate(date != null ? DateFormatUtils.format(date, "yyyy-MM-dd") : "");
				
				dealerChangeDtoList.add(dealerChangeDto);
			}
			return dealerChangeDtoList;
		}
		return null;
	}

	@Override
	public boolean updateChangeTimeFromDealerChange(String dealerNum,String changeDate) {
		try {
			maintainDealerDao.updateChangeTimeFromDealerChange(dealerNum,changeDate);
			return true;
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return false;
	}

	@Override
	public boolean checkDealerExisted(Long dealerNum) {
		try {
			MasterDataDealerInfo info = maintainDealerDao.checkDealerExisted(dealerNum);
			if(info != null){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return false;
	}

	@Override
	public boolean saveDealerChanged(DealerChangeDto dealerChangeDto) {
		try {
			maintainDealerDao.saveDealerChanged(dealerChangeDto);
			return true;
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return false;
	}

	@PostConstruct
	public void runDataConversionThread(){
		DataConversionQueue.start();
	}

	@Override
	public List<DmsDataFixResultDto> handleImportInBackground(String fileName, InputStream in, String templateFileName,
			String templateName, String sheetName) throws AppException {
		try {
			List<DmsDataFixResultDto> result =  FileImportUtils.getImportedRecords(fileName, in, 
			        templateFileName, templateName, sheetName);
//			deleteDataFix();
			saveDmsDataFixFile(result);
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void saveDmsDataFixFile(List<DmsDataFixResultDto> result) throws AppException {
		try {
			if(result != null && !result.isEmpty()){
				maintainDealerDao.saveDmsDataFixFile(result);
			}
		} catch (Exception e) {
			LOGGER.error("saveDmsDataFixFile ERROR");
		}
	}

	@Override
	public List<SmsSendDto> getAllMessageForSend() throws AppException {
		List<Object[]> objList = maintainDealerDao.getAllMessageForSend();
		List<SmsSendDto> smsSendDtoList = new ArrayList<SmsSendDto>();
		if(objList != null && !objList.isEmpty()){
			for(Object[] obj : objList){
				SmsSendDto smsSendDto = new SmsSendDto();
				smsSendDto.setDestMobile(String.valueOf(obj[0]));
				smsSendDto.setContent(String.valueOf(obj[1]));
				smsSendDtoList.add(smsSendDto);
			}
		}
		return smsSendDtoList;
	}

	@Override
	public boolean sendMessage(List<SmsSendDto> smsSendDtoList) throws AppException {
		boolean result = false;
		if(smsSendDtoList != null && !smsSendDtoList.isEmpty()){
			try {
				for(SmsSendDto smsSendDto : smsSendDtoList){
					SMSTextMessage textMessage = new SMSTextMessage();
				    textMessage.setContent(smsSendDto.getContent());
				    textMessage.setMobile(smsSendDto.getDestMobile());
					String resultMsg = HttpSMSProcessUtil.sendMessage(textMessage);
					SmContent smsContent = new SmContent();
				    smsContent.setContent(textMessage.getContent());
				    smsContent.setDestmobile(Long.parseLong(textMessage.getMobile()));
				    smsContent.setHasSent(SmSendStatus.SENT.getValue());
				    smsContent.setMsgId(resultMsg);
				    smContentService.createSmsContent(smsContent);
				}
				result = true;
			} catch (NumberFormatException e) {
				return false;
			}
		}
		return result;
	}

	@Override
	public DataFixPrcResultDto prcDmsDataFix() throws AppException {
		return maintainDealerDao.prcDmsDataFix();
	}

	@Override
	public void deleteDataFix() throws AppException {
		try {
			maintainDealerDao.deleteDataFix();
		} catch (Exception e) {
			LOGGER.error("deleteDataFix Error");
		}
	}
}
